package jsyf.com.task;

import com.alibaba.fastjson.JSONObject;
import jsyf.com.constant.Const;
import jsyf.com.dao.BaseJdbcDao;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @author: 徐波
 * @creat: 2017/12/12 0012 17:54
 * description:
 * 每5分钟从用户资源池中同步二手汇用户
 */
@Component("synchroESHToYF")
public class SynchroESHToYF extends BaseJdbcDao{

    /**用于生成随机用户名的字符串*/
    private static final String NICK_NAME = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private Logger logger = Logger.getLogger(SynchroESHToYF.class);



    /**
     * @param customer  id  mobile  password
    * @Description: 保存/修改用户中心的用户  <br/>
    * @return: java.lang.Integer
    * @throw:
    * @author: 徐波
    * @createTime: 2017/12/12 0012 17:56
    * @Version: V1.0.0
    */
    public Integer save(JSONObject customer){
        String id = customer.getString("id");
        String mobile = customer.getString("mobile");
        int flag = 0;
        if (StringUtils.isBlank(id)) {
            customer.put("ID",super.generateKey());
            customer.put("SOURCE_FLAG",0);
            flag = super.insert("CENTER_DATA_CUSTOMER_RELEVANCE",customer);
        } else {
            JSONObject unique = new JSONObject();
            unique.put("MOBILE",mobile);
            customer.remove("id");
            flag = super.update("CENTER_DATA_CUSTOMER_RELEVANCE",customer,unique);
        }
        return flag;
    }

    /**
     * @param
    * @Description: 定时任务  从用户中心同步二手汇的用户到瀛沣平台  <br/>
    * @return: void
    * @throw:
    * @author: 徐波
    * @createTime: 2017/12/13 0013 12:42
    * @Version: V1.0.0
    */
    //@Scheduled(cron = " 0 0/5 * * * ?")
    public void synchroCustomer(){
        logger.info("**************开始同步******************");
        StringBuffer sql = new StringBuffer();

        //用户池数据
        sql.append(" SELECT center.ID AS id,center.MOBILE AS mobile,center.PASSWORD AS password FROM CENTER_DATA_CUSTOMER_RELEVANCE AS center WHERE 1=1 AND center.DEL_FLAG='0' AND center.SOURCE_FLAG='1' LIMIT 0,1000 \n");
        List<JSONObject> centerCustomerList = super.queryForJsonList(sql.toString());

        if (centerCustomerList == null || centerCustomerList.size() == 0) {
            logger.info("没有新用户");
            return;
        }

        //循环比对
        for (int i = 0; i < centerCustomerList.size(); i++) {
            String mobile = centerCustomerList.get(i).getString("mobile");
            String password = centerCustomerList.get(i).getString("password");
            sql.delete(0,sql.length());
            //瀛沣用户
            sql.append(" SELECT customer.ID AS id,customer.USER_NAME AS userName,customer.PASSWORD AS password FROM S_CUSTOMER AS customer \n");
            sql.append(" WHERE 1=1 AND customer.USER_NAME='");
            sql.append(mobile);
            sql.append("'");
            JSONObject customerFromYF = super.queryForJsonObject(sql.toString());

            if (customerFromYF != null ) {
                /**如果用户名密码一样，则是没有修改的  直接逻辑删除*/
                if (password.equals(customerFromYF.getString("password"))) {
                    //remove
                    logger.info("存在且一样");
                    centerCustomerList.get(i).put("DEL_FLAG",'1');
                    this.save(centerCustomerList.get(i));
                    logger.info("删除成功！");
                } else {
                    /**否则是修改过密码的，更新瀛沣用户表*/
                    logger.info("修改过密码，更新瀛沣表");
                    JSONObject unique = new JSONObject();
                    unique.put("ID",customerFromYF.getString("id"));
                    JSONObject customer = new JSONObject();
                    customer.put("PASSWORD",password);
                    super.update("S_CUSTOMER",customer,unique);
                    centerCustomerList.get(i).put("DEL_FLAG",'1');
                    this.save(centerCustomerList.get(i));
                    logger.info("更新成功！");
                }
            } else {
                logger.info("新用户插入到瀛沣用户表中");
                centerCustomerList.get(i).put("DEL_FLAG",'1');
                this.save(centerCustomerList.get(i));
                this.saveCustomer(centerCustomerList.get(i));
                logger.info("插入成功！");
            }

        }
    }

    /**
     * @param customer
    * @Description: 保存到瀛沣平台  <br/>
    * @return: com.alibaba.fastjson.JSONObject
    * @throw:
    * @author: 徐波
    * @createTime: 2017/12/12 0012 18:54
    * @Version: V1.0.0
    */
    public void saveCustomer(JSONObject customer){

        String id = super.generateKey();
        //用户的唯一标示账户名ACCOUNT，规则为yf加上12位随机数，为主键的后12位
        String account = "yf"+id.substring(20,32);
        //默认为0，个人用户
        String userType = Const.FALSE;
        //默认为0，启用
        String isFlag = Const.FALSE;
        //用户录入方式 0 自然用户注册
        String sourceFlag = Const.FALSE;
        //默认登录错误次数为0
        int loginErrorCount = Const.INT_ZERO;
        //最后一次登录错误时间，在这个时间半小时之内，且错误次数大于指定次数，用户登录需要输入图片验证码
        Date loginLockTime = super.getCurrentTime();
        //更新时间
        Date modifiedTime = super.getCurrentTime();
        //删除时间
        Date delTime = super.getCurrentTime();
        //逻辑删除为默认为0，没有删除
        String delFlag = Const.FALSE;

        String userName = customer.getString("mobile");
        customer.remove("mobile");
        customer.put("ID",id);
        customer.put("USER_NAME",userName);
        customer.put("USER_TYPE",userType);
        customer.put("NICK_NAME", RandomStringUtils.random(8,NICK_NAME));
        customer.put("IS_FLAG",isFlag);
        customer.put("LOGIN_ERROR_COUNT",loginErrorCount);
        customer.put("LOGIN_LOCK_TIME",loginLockTime);
        customer.put("MODIFIED_TIME",modifiedTime);
        customer.put("DEL_TIME",delTime);
        customer.put("DEL_FLAG",delFlag);
        customer.put("SOURCE_FLAG",sourceFlag);
        //用户的唯一标示账户名
        customer.put("ACCOUNT",account);

        Integer flag =super.insert("S_CUSTOMER",customer);
    }

}
